<template>
  <div class="">
    <el-form :inline="true" :model="selectBody" class="demo-form-inline">
      <el-form-item label="请求路径">
        <el-input v-model="selectBody.url" placeholder="请输入请求路径" clearable />
      </el-form-item>
      <el-form-item label="路径描述">
        <el-input v-model="selectBody.description" placeholder="请输入路径描述" clearable />
      </el-form-item>
      <el-form-item label="更新原因">
        <el-input v-model="selectBody.updatedReason" placeholder="请输入更新原因" clearable />
      </el-form-item>

      <el-form-item label="创建人">
        <el-select v-model="selectBody.createUser" placeholder="请选择创建人" filterable clearable style="width: 192px">
          <el-option v-for="item in adminUsers" :key="item.userId" :label="item.username" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="修改人">
        <el-select v-model="selectBody.updateUser" placeholder="请输入修改人" filterable clearable style="width: 192px">
          <el-option v-for="item in adminUsers" :key="item.userId" :label="item.username" :value="item.userId" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker v-model="selectBody.createdTime" type="date" placeholder="请选择创建时间" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="handlerAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableData" style="width: 100%" stripe>
      <el-table-column v-for="(row, rowIndex) in tableHead" :key="rowIndex" :label="row.label" :prop="row.prop"
        :formatter="row.formatter" :width="row.width" />
      <el-table-column align="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <div class="demo-pagination-block">
        <el-pagination v-model:current-page="selectBody.curPage" v-model:page-size="selectBody.pageSize"
          :page-sizes="[10, 20, 30, 50]" layout="sizes, prev, pager, next" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <el-dialog v-model="dialogData.showDialog" :title="dialogData.title" width="500" center>
      <el-form label-width="auto" :model="changeData" style="max-width: 600px">
        <el-form-item label="数据ID" v-if="false">
          <el-input v-model="changeData.id" />
        </el-form-item>
        <el-form-item label="请求地址">
          <el-input v-model="changeData.url" :disabled="dialogData.type == 1" />
        </el-form-item>
        <el-form-item label="	请求描述">
          <el-input v-model="changeData.description" />
        </el-form-item>
        <el-form-item label="更新原因">
          <el-input v-model="changeData.updatedReason" />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="changeData.createUser" disabled />
        </el-form-item>
        <el-form-item label="	修改人">
          <el-input v-model="changeData.updateUser" disabled />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogData.showDialog = false">取消</el-button>
          <el-button type="primary" @click="handConfirm">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { recordList, recordAdd, recordUpdate, recordDelete } from '@/network/manage/api_requestPath.js'
import { recordAdminUser } from '@/network/manage/api_commonSystemCommon.js'
import { CODE_SUCCESS } from '@/common_js/common_variable'
import { ElNotification, ElMessageBox } from 'element-plus'
import { cloneDeep } from 'lodash-es'

export default {
  name: 'RequestPath',
  components: {},
  setup() {
    // const store = useCounterStore()
    const loading = ref(false)
    let selectBody = reactive({
      url: '',
      description: '',
      updatedReason: '',
      createUser: '',
      updateUser: '',
      createdTime: '',
      curPage: 1,
      pageSize: 10,
    })
    let adminUsers = ref([])
    const getAdminUser = () => {
      recordAdminUser().then(res => {
        adminUsers.value = res.data
      })
    }
    onMounted(() => {
      getAdminUser()
    })

    let tableHead = ref([
      // {label: '数据ID', prop: 'id', width: 100},
      
      { label: '请求地址', prop: 'url' },
      { label: '请求描述', prop: 'description' },
      { label: '更新原因', prop: 'updatedReason' },
      { label: '创建人', prop: 'createUser' },
      { label: '修改人', prop: 'updateUser' },
      { label: '创建时间', prop: 'createdTime' },
      { label: '修改时间', prop: 'updatedTime' },
      {
        label: '是否生效',
        prop: 'deleted',
        formatter: (row, column, cellValue) => {
          return cellValue ? '否' : '是'
        },
      },
    ])
    let tableData = ref([])
    let total = ref(1)
    const onSubmit = () => {
      loading.value = true
      recordList(selectBody)
        .then(res => {
          if (res.code != CODE_SUCCESS) {
            return
          }
          tableData.value = res.data.dataList
          total.value = res.data.total
          selectBody.curPage = res.data.curPage
        })
        // .catch(error => {
        //   ElNotification({
        //     title: '请求失败',
        //     message: error.message,
        //     type: 'error',
        //   })
        // })
        .finally(() => {
          loading.value = false
        })
    }
    // 修改数据
    const handleEdit = (idx, row) => {
      dialogData.showDialog = true
      dialogData.title = '请输入修改数据'
      dialogData.type = 1
      Object.assign(changeData, cloneDeep(row))
    }
    const handleDelete = (idx, row) => {
      ElMessageBox.confirm(
        '请确认是否删除该数据？',
        '警告！',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          recordDelete(row.id)
            .then(res => {
              if (res.code != CODE_SUCCESS) {
                ElNotification({
                  title: '删除失败',
                  message: res.message,
                  type: 'error',
                })
                return
              }
              onSubmit()
            })
          // .catch(error => {
          //   ElNotification({
          //     title: '删除失败',
          //     message: error.message,
          //     type: 'error',
          //   })
          // })
        })
        .catch(() => {
          // 取消
        })
    }
    // 每页条数改变
    const handleSizeChange = newSize => {
      selectBody.pageSize = newSize
      onSubmit()
    }
    // 当前页改变
    const handleCurrentChange = newPage => {
      selectBody.curPage = newPage
      onSubmit()
    }

    // 新增数据
    const handlerAdd = () => {
      dialogData.showDialog = true
      dialogData.title = '请输入新增数据'
      dialogData.type = 0
      resetaddDataSample()
    }
    let dialogData = reactive({
      showDialog: false,
      title: '',
      type: 0 // 0为添加数据，1为修改数据
    })
    const resetaddDataSample = () => {
      Object.assign(changeData, {
        id: "",
        url: "",
        description: "",
        updatedReason: "",
        createUser: '',
        updateUser: ''
      })
    }
    let changeData = reactive({})
    const handConfirm = () => {
      if (dialogData.type === 0) {
        console.log('当前为添加');
        delete changeData.createdTime
        delete changeData.updatedTime
        recordAdd(changeData)
          .then(res => {
            if (res.code != CODE_SUCCESS) {
              ElNotification({
                title: '添加失败',
                message: error.message,
                type: 'error',
              })
              return
            }
            onSubmit()
          })

        // .catch(error => {
        //   ElNotification({
        //     title: '添加失败',
        //     message: error.message,
        //     type: 'error',
        //   })
        // })
      } else if (dialogData.type === 1) {
        console.log('当前为修改')
        const cpChangeData = reactive(changeData)
        delete cpChangeData.createdTime
        delete cpChangeData.updatedTime
        console.log(changeData);
        console.log(cpChangeData);
        recordUpdate(cpChangeData)
          .then(res => {
            if (res.code != CODE_SUCCESS) {
              ElNotification({
                title: '修改失败',
                message: error.message,
                type: 'error',
              })
              return
            }
            onSubmit()
          })
        // .catch(error => {
        //   ElNotification({
        //     title: '修改失败',
        //     message: error.message,
        //     type: 'error',
        //   })
        // })
      }
      console.log(changeData);
      dialogData.showDialog = false
    }
    return {
      selectBody,
      adminUsers,
      onSubmit,
      loading,
      tableHead,
      tableData,
      total,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      handlerAdd,
      dialogData,

      resetaddDataSample,
      changeData,
      handConfirm
    }
  },
}

</script>

<style scoped>
.example-showcase .el-loading-mask {
  z-index: 9;
}

@media (min-width: 768px) {
  .type-select :deep(.el-select) {
    width: 400px;
  }
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>